﻿namespace Dyao.Book.Application
{
    public class TaskCenterRuleManager
    {
        private static Dictionary<string, TaskCenterRuleExcutingInfo> _taskCenterRuleExcutorDict = new Dictionary<string, TaskCenterRuleExcutingInfo>();

        static TaskCenterRuleManager()
        {
            var executorTypeList = new List<Type>()
            {
                typeof(TestTaskRuleExcutor),
                typeof(UserTaskIntervalExcutor),
                typeof(UserSameTaskRunningTaskRuleExecutor),
            };

            #region 加载规则执行器相关信息

            var dict = _taskCenterRuleExcutorDict;

            foreach (var type in executorTypeList)
            {
                var attributes = type.GetCustomAttributes(typeof(TaskCenterRuleNameAttribute), false);
                if (attributes.Length == 0) continue;

                var nameAttribute = attributes[0] as TaskCenterRuleNameAttribute;

                var hasSettings = false;
                var isNeedLoadSettings = false;
                Type settingType = null;

                var faces = type.GetInterfaces();
                var genType = faces.FirstOrDefault(face => face.IsGenericType && face.GetGenericTypeDefinition() == typeof(ITaskRuleExcutor<>));

                isNeedLoadSettings = faces.Any(face => face == typeof(ITaskRuleSettingsLoader));

                if (genType != null)
                {
                    hasSettings = true;
                    settingType = genType.GenericTypeArguments[0];

                    if (isNeedLoadSettings)
                    {
                        var settingObj = Activator.CreateInstance(settingType);
                    }
                }

                dict.Add(nameAttribute.Rulekey, new TaskCenterRuleExcutingInfo
                {
                    RuleKey = nameAttribute.Rulekey,
                    Name = nameAttribute.DisplayName,
                    HasSettings = hasSettings,
                    IsNeedLoadSettings = isNeedLoadSettings,
                    Type = type,
                    SettingType = settingType,
                });
            }

            #endregion // end 加载规则执行器相关信息
        }

        public static IReadOnlyDictionary<string, TaskCenterRuleExcutingInfo> GetTaskCenterRules()
        {
            return _taskCenterRuleExcutorDict;
        }

        public static TaskCenterRuleExcutingInfo GetRuleExcutorTypeByKey(string key)
        {
            GetTaskCenterRules().TryGetValue(key, out var taskCenterRuleExcutingInfo);
            return taskCenterRuleExcutingInfo;
        }

    }
}
